<?php
//购物车信息控制器
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class ShopController extends Controller
{
    //加载商品
    public function index()
    {
       $list = \DB::table("goods")->get();
       return view("shop.index",["list"=>$list]);
    }
    
    //购物车添加商品
    public function add($id)
    {
        //获取要放入购物车中的商品
        $shop = \DB::table("goods")->where("id",$id)->first();
        $shop->m = 1; //添加一个购买量
        //ar_dump($shop);
        //先判断购物车中是否包含此商品
        if(session()->has("shoplist.{$id}")){
            //商品数量加1
            $ob = session()->get("shoplist.{$id}");
            //var_dump($ob);
            $ob->m += 1;
            session()->put("shoplist.{$id}",$ob);
        }else{
            //放入购物车中
            session()->put("shoplist.{$id}",$shop);
        }
        //session()->flush();
        return view("shop.show",["shoplist"=>session()->get("shoplist")]);
    }
    
    //查看购物车
    public function show()
    {
        return view("shop.show");
    }
    
    //删除购物车中的某个商品
    public function del($id)
    {
        session()->forget('shoplist.'.$id);
        return view("shop.show");
    }
    
    //清空购物车
    public function clear()
    {
        session()->put('shoplist',[]);
        return view("shop.show");
    }
}